<template>
  <div>
    <div class="mainPpt">
      <div class="topHead">
        <el-button @click="$router.go(-1)" type="primary" class="btn" size="mini"><i class="el-icon-d-arrow-left"></i>返回</el-button>
        <div class="title">{{title}}</div>
      </div>
      <div id="container">
        <div class="pdfArea">
          <pdf :src="src"
               ref="pdf"
               v-show="loadedRatio===1"
               :page="currentPage"
               @num-pages="pageCount=$event"
               @progress="loadedRatio = $event"
               @page-loaded="currentPage=$event"
               @loaded="loadPdfHandler"
               @link-clicked="currentPage = $event"
               style="display: inline-block;width:100%;box-shadow:0px 0px 80px rgba(0, 0, 0, 0.2)"
               id="pdfID"></pdf>
        </div>

        <!-- 上一页、下一页 -->
        <div class="right-div">
          <div class="time1">{{lookTime}}</span></div>
          <div class="time">学习时长：<span style="color: #0076ca;">{{studyTime}}</span></div>
          <div class="right-btn">
            <!-- 输入页码 -->
            <div class="pageNum">
              <input v-model.number="currentPage"
                     type="number"
                     class="inputNumber"
                     @input="inputEvent()"> / {{pageCount}}
            </div>
            <div @click="changePdfPage('first')"
                 class="turn">
              首页
            </div>
          <!-- 在按钮不符合条件时禁用 -->
            <div @click="changePdfPage('pre')"
                 class="turn-btn"
                 :style="currentPage===1?'cursor: not-allowed;':''">
              上一页
            </div>
            <div @click="changePdfPage('next')"
                 class="turn-btn"
                 :style="currentPage===pageCount?'cursor: not-allowed;':''">
              下一页
            </div>
            <div @click="changePdfPage('last')"
                 class="turn"
                 :style="dataPage<pageCount-1?'cursor: not-allowed;':''">
              尾页
            </div>
          </div>
        </div>

        <!-- 加载未完成时，展示进度条组件并计算进度 -->
        <div class="progress"
             v-show="loadedRatio!==1">
          <el-progress type="circle"
                       :width="70"
                       color="#53a7ff"
                       :percentage="Math.floor(loadedRatio * 100)"></el-progress>
          <br>
          <!-- 加载提示语 -->
          <span>{{remindShow}}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  name:'pptCourse',
  components: {
    pdf
  },
  computed: {
  },
  data () {
    return {
      // ----- loading -----
      remindText: {
        loading: '加载文件中，文件较大请耐心等待...',
        refresh: '若卡住不动，可刷新页面重新加载...'
      },
      remindShow: '加载文件中，文件较大请耐心等待...',
      intervalID: '',
      // ----- vuepdf -----
      // src静态路径: /static/xxx.pdf
      // src服务器路径: 'http://.../xxx.pdf'
      src: '',
      // 当前页数
      currentPage: 0,
      // 总页数
      pageCount: 0,
      // 加载进度
      loadedRatio: 0,
      courseName:'',
      courseType:'',
      privateId:'',
      courseId:'',
      nowTime:null,//当前时间
      studyTime:0,//学习时间
      startTime:null,//初始化时间
      title:'',
      sTime:'',
      target:'',
      detailId:'',
      dataPage:'',//数据库中记录的最大学习页码
      lookTime:'',//每页ppt的观看时间
      timer:null,
    }
  },
  head() {
      return {
        title: this.title,
      }
  },
  created () {
    // this.prohibit()
    this.getData()

  },
  beforeDestroy() {
    if(this.sTime) {
    　　　　clearInterval(this.sTime); //关闭
    　}  //利用vue的生命周期函数
    if(this.timer) {
    　　　　clearInterval(this.timer); //关闭
    　}  //利用vue的生命周期函数
  },
  destroyed () {
    // 在页面销毁时记得清空 setInterval
    clearInterval(this.intervalID)
  },
  mounted () {
    // 更改 loading 文字
    this.intervalID = setInterval(() => {
      this.remindShow === this.remindText.refresh
        ? this.remindShow = this.remindText.loading
        : this.remindShow = this.remindText.refresh
    }, 4000)
    // 监听滚动条事件
    // this.listenerFunction()
    //页面实例化的时候开始计时
    this.startTime = (new Date())
    //此次页面的学习开始时间
    this.thisTime = (new Date())
  },

  methods: {
    //添加学习记录（a为最大学习页码数，b为学习时间）
    addStudyCenter(a,b){
      var that = this;
      this.$axios.$post('/f/saveUserVideoRecord?courseId='+this.courseId+'&courseType='+this.type+'&pages='+a+'&detailId=' +this.detailId + '&rootCourseId='+this.privateId+'&studyTime='+b+'&target='+this.target)
      .then(function (response) {

      })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
    },
    getData(){
        var that = this;
        this.$axios.$post("/f/course?id="+this.$route.params.id)
        .then(function (response) {
          let url = that.$axios.defaults.baseURL + response.data.course.courseInfo.educationCoursePptDetailsList[0].educationDoc.fileUrl
          that.src = url
          let data = Object.assign(response.data.course,response.data.course.courseInfo)
          that.title = data.courseName;
          that.type = data.courseType;
          that.privateId = data.privateId;
          that.courseId = data.courseId;
          that.detailId = data.courseInfo.educationCoursePptDetailsList[0].id
          that.lookTime = data.lookTime

          //每页观看时间倒计时
          that.timer = setInterval(()=>{
            that.lookTime --
            //倒计时等于0后，自动翻页
            if(that.lookTime == 0){
              that.changePdfPage('next')
              that.lookTime = data.lookTime
            }
          },1000)


          if(Number(data.presentPrice)==0){
              that.target = "0";
          }
          else{
              that.target = "1";
          }
          //获取记录中学习到的最大页码
          if(response.data.userStudy[0]){
            that.dataPage = response.data.userStudy[0].pages
          }else{
            that.dataPage = 1 //首次的话，默认最大页码学习数为1
          }
          let time
          if(response.data.userStudy.length!=0){
            time = response.data.userStudy[0].studyTime
          }else{
            time = 0
          }
          that.startTime = Date.parse(that.startTime) - time*1000
          that.sTime = setInterval(()=>{
            //获取当前时间，减去进入页面时间则是现有的学习时间，总的学习时间还需加上服务器返回的总时间
            const total = Date.parse(new Date()) - that.startTime;
            const minutes = Math.floor((total / 1000 / 60) % 60);
            const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
            that.studyTime = hours + '时' + minutes + '分'
            let iTime = Math.floor(total / 1000);
            //如果当前页码小于返回数据中的页码，则不传此次页码数
            let upPages = null
            if(that.currentPage>that.dataPage){
              upPages = that.currentPage
              that.dataPage = upPages
            }else{
              upPages = that.dataPage
            }
            that.addStudyCenter(upPages,iTime)
          },3000)

        })
        .catch(function (error) {
          // handle error
          console.log(error);
        })
    },
    // 监听滚动条事件
    // listenerFunction (e) {
    //   document.getElementById('container').addEventListener('scroll', true)
    // },
    // 页面回到顶部
    toTop () {
      document.getElementById('container').scrollTop = 0
    },
    // 输入页码时校验
    inputEvent () {
      if (this.currentPage > this.dataPage) {
        // 1. 跳转页码不能大于学习记录中存放的最大学习页码
        this.currentPage = this.dataPage
      } else if (this.currentPage < 1) {
        // 2. 小于min
        this.currentPage = 1
      }
      // if (this.currentPage > this.pageCount) {
      //   // 1. 大于max
      //   this.currentPage = this.pageCount
      // } else if (this.currentPage < 1) {
      //   // 2. 小于min
      //   this.currentPage = 1
      // }
    },
    // 切换页数
    changePdfPage (val) {
      if (val === 'pre' && this.currentPage > 1) {
        // 切换后页面回到顶部
        this.currentPage--
        this.toTop()
      } else if (val === 'next' && this.currentPage < this.pageCount) {
        this.currentPage++
        this.toTop()
      } else if (val === 'first') {
        this.currentPage = 1
        this.toTop()
      } else if (val === 'last' && this.currentPage < this.pageCount) {
        this.currentPage = this.pageCount
        this.toTop()
      }
    },

    // pdf加载时
    loadPdfHandler (e) {
      // 加载的时候先加载第一页
      this.currentPage = 1
    },

    // 禁用鼠标右击、F12 来禁止打印和打开调试工具
    prohibit () {
      // console.log(document)
      document.oncontextmenu = function () {
        return false
      }
      document.onkeydown = function (e) {
        if (e.ctrlKey && (e.keyCode === 65 || e.keyCode === 67 || e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 80 || e.keyCode === 83 || e.keyCode === 85 || e.keyCode === 86 || e.keyCode === 117)) {
          return false
        }
        if (e.keyCode === 18 || e.keyCode === 123) {
          return false
        }
      }
    }
  }
}
</script>

<style scoped>
.mainPpt{
  width: 100vw;
  height: 100vh;
}
#container {
  overflow: auto;
  /* height: 800px; */
  font-family: PingFang SC;
  display: flex;
  /* justify-content: center; */
  position: relative;
  top: 60px;
  align-items: center;
  padding: 50px;
  height: calc(100% - 60px);
  background-color: #f5f7fa;
}
.topHead{
  height: 60px;
  background-color: #0076ca;
  position: fixed;
  top: 0;
  width: 100%;
  display: flex;
  padding: 0 50px;
  align-items: center;
  /* justify-content: center; */
  z-index: 100;
}
.btn{
  height: 30px;
  position: fixed;
  left: 50px;
}
.title{
  font-size: 18px;
  font-weight: bold;
  width: 100%;
  text-align: center;
  color: #ffffff;
}
.time{
  font-size: 16px;
  /* width: 160px; */
  text-align: center;
  /* top: 200px; */
  bottom: calc(50% - 230px);
  position: fixed;
}
.time1{
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 15px;
  background-color: #0076ca;
  color: #ffffff;
  font-size: 16px;
  /* width: 160px; */
  text-align: center;
  /* top: 120px; */
  top: calc(50% - 230px);
  position: fixed;
}
.right-div{
  width: 20%;
  display: flex;
  justify-content: center;
  height: 100%;
}
/* 右侧功能按钮区 */
.right-btn {
  position: fixed;
  /* right: 5%; */
  bottom: calc(50% - 188px);
  width: 160px;
  /* height: calc(100% - 100px); */
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  z-index: 99;
  flex-direction: column;
  align-items: center;
}

.pdfArea {
  width: 80%;
  /* height: 100%; */
  display: flex;
  align-items: center;
}

/* ------------------- 输入页码 ------------------- */
.pageNum {
  margin: 10px 0;
  font-size: 18px;
}
/*在谷歌下移除input[number]的上下箭头*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
/*在firefox下移除input[number]的上下箭头*/
input[type='number'] {
  -moz-appearance: textfield;
}

.inputNumber {
  border-radius: 8px;
  border: 1px solid #999999;
  height: 35px;
  font-size: 18px;
  width: 60px;
  text-align: center;
}

.inputNumber:focus {
  border: 1px solid #00aeff;
  background-color: rgba(18, 163, 230, 0.096);
  outline: none;
  transition: 0.2s;
}

/* ------------------- 切换页码 ------------------- */
.turn {
  background-color: #0056ca;
  opacity: 0.7;
  color: #ffffff;
  height: 70px;
  width: 70px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 0;
}

.turn-btn {
  background-color: #0076ca;
  opacity: 0.6;
  color: #ffffff;
  height: 70px;
  width: 70px;
  border-radius: 50%;
  margin: 5px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.turn-btn:hover,
.turn:hover {
  transition: 0.3s;
  opacity: 0.5;
  cursor: pointer;
}

/* ------------------- 进度条 ------------------- */
.progress {
  position: absolute;
  right: 50%;
  top: 50%;
  text-align: center;
}
.progress > span {
  color: #199edb;
  font-size: 14px;
}
</style>
